import React, { PureComponent, Fragment } from 'react';
import { Form, Input, Button, Icon, Select } from 'antd';
// import { connect } from 'dva';
import lodash from 'lodash';
// import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import { getJob, validatorCron } from '../../../services/alarm-job-controller';
import { NotificationRuleArray, TimeUnitArray } from '../../../utils/enum';
// import classNames from 'classnames';
import styles from './MetricConfig.less';

@Form.create()
export default class MetricConfig extends PureComponent {

  render() {
    const { jobConfigData, saveForm, form } = this.props;
    const { getFieldDecorator, getFieldValue } = form;
    if (saveForm instanceof Function) saveForm(form);
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 },
        md: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
        md: { span: 12 },
      },
    };
    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 18, offset: 3 },
        md: { span: 12, offset: 7 },
      },
    };
    const rule = getFieldValue('rule');
    return (
      <Form layout="horizontal" className={styles.form}>
        <Form.Item label="告警名称" hasFeedback {...formItemLayout}>
          {getFieldDecorator('name', {
            initialValue: jobConfigData ? jobConfigData.name : undefined,
            validateFirst: true,
            rules: [
              { required: true, whitespace: false, min: 6, max: 63, message: '告警名称长度必须6~63字符' },
              {
                validator(_, value, callback) {
                  if (!value || lodash.trim(value) === '') {
                    callback(["告警名称不能为空"]);
                    return;
                  }
                  getJob(value).then(result => {
                    if (result) {
                      callback(["告警名称重复"]);
                    } else {
                      callback([]);
                    }
                  }).catch(() => callback([]));
                },
              },
            ],
          })(
            <Input placeholder="告警名称" />
          )}
        </Form.Item>

        <Form.Item label="Cron表达式" {...formItemLayout}>
          {getFieldDecorator('cron', {
            initialValue: jobConfigData ? jobConfigData.cron : undefined,
            validateFirst: true,
            rules: [
              { required: true, whitespace: false, min: 11, max: 127, message: 'Cron表达式至少有11个字符' },
              {
                validator(_, value, callback) {
                  if (!value || lodash.trim(value) === '') {
                    callback(["Cron表达式不能为空"]);
                    return;
                  }
                  validatorCron({ cron: value, num: 5 }).then(result => {
                    if (!result) {
                      callback(["Cron表达式错误"]);
                    } else {
                      callback([]);
                    }
                  }).catch(() => callback([]));
                },
              },
            ],
          })(
            <Input
              placeholder="Cron表达式，如：0 */1 * * * ?"
              addonBefore={(
                <Icon style={{ cursor: 'pointer' }} type="info-circle" theme="outlined" title="示例" />
              )}
              addonAfter={(
                <Icon style={{ cursor: 'pointer' }} type="clock-circle" theme="outlined" title="验证" />
              )}
            />
          )}
        </Form.Item>

        <Form.Item label="通知规则" {...formItemLayout}>
          {getFieldDecorator('rule', {
            initialValue: jobConfigData ? jobConfigData.rule : undefined,
            validateFirst: true,
            rules: [
              { required: true, whitespace: false, message: '通知规则不能为空' },
            ],
          })(
            <Select placeholder="通知规则" allowClear={false}>
              {NotificationRuleArray.map(item => (<Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>))}
            </Select>
          )}
        </Form.Item>

        {rule === 'frequency' ? (
          <Fragment>
            <Form.Item label="频率时间段" required {...formItemLayout}>
              {getFieldDecorator('frequencyTimeLength', {
                initialValue: jobConfigData ? jobConfigData.frequencyTimeLength : undefined,
                validateFirst: true,
                rules: [
                  {
                    validator(_, value, callback) {
                      if (!value || lodash.trim(value) === '') {
                        callback(["Cron表达式不能为空"]);
                        return;
                      }
                      callback([]);
                    },
                  },
                ],
              })(
                <Input
                  placeholder="频率时间段(必须是整数)"
                  addonAfter={
                    getFieldDecorator('frequencyTimeLengthUnit', { initialValue: 'second' })(
                      <Select style={{ width: 70 }}>
                        {TimeUnitArray.map(item => (<Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>))}
                      </Select>
                    )
                  }
                />
              )}
            </Form.Item>

            <Form.Item label="告警次数上限" required {...formItemLayout}>
              {getFieldDecorator('frequencyCountMax', {
                initialValue: jobConfigData ? jobConfigData.frequencyCountMax : undefined,
                validateFirst: true,
                rules: [
                  {
                    validator(_, value, callback) {
                      if (!value || lodash.trim(value) === '') {
                        callback(["Cron表达式不能为空"]);
                        return;
                      }
                      callback([]);
                    },
                  },
                ],
              })(
                <Input placeholder="告警次数上限(大于等于此值发送通知)" addonAfter="次" />
              )}
            </Form.Item>
          </Fragment>
        ) : ''}

        {rule === "flatline" ? (
          <Form.Item label="持续时间上限" required {...formItemLayout}>
            {getFieldDecorator('flatlineTimeLengthMax', {
              initialValue: jobConfigData ? jobConfigData.flatlineTimeLengthMax : undefined,
              validateFirst: true,
              rules: [
                {
                  validator(_, value, callback) {
                    if (!value || lodash.trim(value) === '') {
                      callback(["Cron表达式不能为空"]);
                      return;
                    }
                    callback([]);
                  },
                },
              ],
            })(
              <Input
                placeholder="持续时间上限(必须是整数，大于等于此值发送通知)"
                addonAfter={
                  getFieldDecorator('flatlineTimeLengthMaxUnit', { initialValue: 'second' })(
                    <Select style={{ width: 70 }}>
                      {TimeUnitArray.map(item => (<Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>))}
                    </Select>
                  )
                }
              />
            )}
          </Form.Item>
        ) : ''}

        <Form.Item label="任务描述信息" {...formItemLayout}>
          {getFieldDecorator('description', {
            initialValue: jobConfigData ? jobConfigData.description : undefined,
            rules: [
              { required: false, max: 1023, message: '任务描述信息长度不能超过1023个字符' },
            ],
          })(
            <Input.TextArea placeholder="任务描述信息" rows={5} autosize={{ minRows: 5, maxRows: 10 }} />
          )}
        </Form.Item>

        <Form.Item {...submitFormLayout}>
          <Button>配置监控项</Button>
        </Form.Item>
      </Form>
    );
  }
}
